import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
// 导入请求用户信息的axios请求
import { getUserInfoAPI } from '@/api/index'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    token: '',
    userinfo: {} // 保存用户信息 id,username.nickname
  },
  getters: {
    // 原始写法：username(state){
    //   return state.userinfo.username
    // }
    username: state => state.userinfo.username,
    nickname: state => state.userinfo.nickname,
    user_pic: state => state.userinfo.user_pic
  },
  mutations: {
    // 保存token
    updateToken (state, newToken) {
      state.token = newToken
    },
    // 保存用户信息
    updateUserInfo (state, info) {
      state.userinfo = info
    }
  },
  actions: {
    // 初始化用户基本信息的action函数
    async  getUserInfoActions (store) {
      const { data: res } = await getUserInfoAPI()
      if (res.code === 0) {
        store.commit('updateUserInfo', res.data)
      }
    }
  },
  modules: {
  },
  plugins: [
    createPersistedState() // 注入持久化插件
  ]
})
// vuex-persistedstate这个工具让vuex进行持久化管理
